
package com.limoilux.cobolux.core;

import org.eclipse.core.resources.ICommand;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IProjectDescription;
import org.eclipse.core.resources.IProjectNature;
import org.eclipse.core.runtime.CoreException;

import com.limoilux.cobolux.core.builder.CoboluxBuilder;


public class CoboluxNature implements IProjectNature
{
	public static final String NATURE_ID = "com.limoilux.cobolux.nature";

	private IProject project = null;

	public CoboluxNature()
	{

	}

	@Override
	public void configure() throws CoreException
	{
		IProjectDescription desc = null;

		if (this.project != null)
		{
			desc = this.project.getDescription();

			this.addBuilder(desc);
			this.addNature(desc);

			desc.setComment("Cobolux test project");

			this.project.setDescription(desc, null);
		}
	}

	@Override
	public void deconfigure() throws CoreException
	{
		// TODO implementé la deconfiguration du projet.
		@SuppressWarnings("unused")
		IProjectDescription desc = null;

		if (this.project != null)
		{
			desc = this.project.getDescription();

		}
	}

	@Override
	public IProject getProject()
	{
		return this.project;
	}

	@Override
	public void setProject(IProject project)
	{
		this.project = project;
	}

	private void addBuilder(IProjectDescription desc)
	{
		ICommand[] olds = null;
		ICommand[] news = null;
		ICommand command = null;
		boolean absent = true;

		olds = desc.getBuildSpec();

		for (int i = 0; i < olds.length && absent; i++)
		{
			command = olds[i];

			if (command.getBuilderName() == CoboluxBuilder.BUILDER_ID)
			{
				absent = false;
			}
		}

		if (absent)
		{
			command = desc.newCommand();
			command.setBuilderName(CoboluxBuilder.BUILDER_ID);

			news = new ICommand[olds.length + 1];
			System.arraycopy(olds, 0, news, 0, olds.length);
			news[news.length - 1] = command;

			desc.setBuildSpec(news);
		}
	}

	private void addNature(IProjectDescription desc) throws CoreException
	{
		String[] oldNatures = null;
		String[] newNatures = null;

		if (!desc.hasNature(NATURE_ID))
		{
			oldNatures = desc.getNatureIds();
			newNatures = new String[oldNatures.length + 1];

			System.arraycopy(oldNatures, 0, newNatures, 0, oldNatures.length);

			newNatures[newNatures.length - 1] = NATURE_ID;

			desc.setNatureIds(newNatures);
		}
	}
}
